<?php
/**
 * 我的微信模块
 * @author 七里枫香
 * 
 *
 */
namespace Member\Controller;

//数据分页
use Think\Page;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class WechatController extends MemberController {

	//首次关注设置
    public function index(){
    	//如果是提交
    	if(IS_POST){
    		//添加
    		$eventLogic = D('Event','Logic');
    		$status = $eventLogic->update();
			//dump($eventLogic->getLastSql());exit;
    		if($status !== false){
    		    $this->success('添加成功');
    		}else{
    		    $this->error('添加失败');
    		}
    		
		//$this->display();
    		
    	}else{
    		//获取全部的模块信息
    		$moudle = D('Module','Logic');
    		$modules = $moudle->allLists();
    		$this->assign('modules',$modules);
    		
    		//获取全部的图文消息
    		$newsmsgLogic = D('Newsmsg','Logic');
    		$newsmsgs = $newsmsgLogic->allLists();
    		$this->assign('newsmsgs',$newsmsgs);
    		
    		//获取之前的记录
    		$eventLogic = D('Event','Logic');
    		//获取用户的信息
    		$userEvent = $eventLogic->getUserEvent('subscribe',UID);
    		//如果用户的信息存在
    		if($userEvent){
    		    $this->assign('userEvent',$userEvent);
    		}
//     		dump($userEvent);exit;
//     		dump($userEvent);exit;
    		//显示界面
    		$this->display();
    	}
    }
    
    /**
     * 自定义菜单设置
     */
    public function classify(){
    	
    	if(IS_POST){
    	    //实例化
    		$classifyLogic = D('Classify','Logic');
    		$data = $classifyLogic->create();
    		if($data['id']==0){
    			$data['sort'] = $classifyLogic->where(array('uid'=>UID,'pid'=>$data['pid']))->count();
    		}
    		//获取信息内容
    		$type = I('post.MsgType','0','intval');
    		//如果是文本内容
    		if($type == '0'){
    		    $config['msgtype'] = 'text';
    		    
    		    $text = I('post.text');
    		    
    		    $textmsgLogic = D('Textmsg','Logic');
    		    $textid = $textmsgLogic->saveData($text);
    		    
    		    $config['msgid'] = $textid;
    		    
    		    
    		    
    		}else if($type == '1'){
    		    //如果是多图文消息
    		    $MaterialId = I('post.MaterialId');

    		    $TextNews = D('TextNews','Logic');
    		    $res = $TextNews->savedata($MaterialId);
    		    $config['msgtype'] = $res['msgtype'];
    		    $config['msgid'] = $res['msgid'];
    		    
    		}else{
    		    //如果是连接网址
    			$config['msgtype'] = 'url';
    			$config['url'] = I('post.url');
    		}
    		
    		$data['config'] = serializeMysql($config);
			$num = $classifyLogic->where(array('uid'=>UID,'pid'=>0))->count();
    		if($num > 3 ){
    			//$this->ajaxReturn(array('msg'=>'操作失败,一级菜单不能大于三个'));
    			$this->error('操作失败,一级菜单不能大于三个');
    		}else {
    			$id = $classifyLogic->saveMenu($data);
    			
    			if($id > 0){
    				$this->success('操作成功');
    				redirect(U('classify'));
    			}else{
    				$this->error('操作失败');
    			}
    		}

    	}else{
    		
    		//显示相关数据信息
    		$classifyLogic = D('Classify','Logic');
    		//获取树
    		$menu = $classifyLogic->getMenu();
    		//获取全部的顶级菜单
    		$parentMenu = $classifyLogic->where(array('uid'=>UID,'pid'=>0))->field('id,title')->order('sort asc')->select();
    		
    		$id = I('get.id',0,'intval');
    		//如果当前是更新数据，获取当前的数据信息
    		if($id > 0){
    		    $menuInfo = $classifyLogic->where(array('uid'=>UID,'id'=>$id))->find();
    			$menuInfo['config'] = serializeMysql($menuInfo['config'],1);
    			//如果是文本消息
    			if($menuInfo['config']['msgtype'] == 'text'){
    				
    				$map = array(
    				    'uid'=>UID,
    					'id'=>$menuInfo['config']['msgid'],
    				);
    				
    				$textmsgLogic = D('Textmsg','Logic');
    				//获取文本消息
    			    $menuInfo['config']['textmsg'] = $textmsgLogic->where($map)->find();
    			    
    			}
    			
    			$this->assign('menuInfo',$menuInfo);
//     			dump($menuInfo);exit;
    			$this->assign('update',1);
    			
    		}
    		
    		//全部的一级菜单
    		$this->assign('parentMenu',$parentMenu);
    		//全部的自定义菜单
    		$this->assign('menu',$menu);
    		
    		//获取全部的模块信息
    		$TextNews = D('TextNews','Logic');
			$moudles_news = $TextNews->moudles_news();
			$this->assign('moudles_news',$moudles_news);
// 			print_r($menuInfo);exit;
    		$this->display();
    	}
    	
    	
    }
    
    /**
     * 删除菜单
     */
    public function delClassify($id){
    	//显示相关数据信息
    	$classifyLogic = D('Classify','Logic');
    	$boolean = $classifyLogic->deleteOne($id);
    	
    	if($boolean && $boolean > 0){
    		redirect(U('classify'));
//     	    $this->success('删除成功');
    	}else{
    	    $this->error('删除失败');
    	}
    }
    
    /** 
    *
    * 发布菜单  
    * @copyright Copyright&copy; 2015, 聚成网络 
    * @author Jucheng     
    * @date   2015-4-27  
    * 
    */
    public function publishClassify(){
    	
    	$userconfigLogic = D('Userconfig','Logic');
    	
    	//获取用户accesstoken
    	//$access_token = $userconfigLogic->access_token();
    	$access_token = $this->getAccessToken();
    	//判断是不是正确的值
    	/* if(empty($access_token) || isset($access_token['errcode'])){
			//$this->error('获取access_token错误,'.$access_token['errmsg']);
    	    $data = array(
    	        'status'=>0,
    	    	'msg'=>$access_token['errmsg']
    	    );
    	    $this->ajaxReturn($data,'JSON');
    	} */
    	
    	//显示相关数据信息
    	$classifyLogic = D('Classify','Logic');
    	//获取树
    	$menu = $classifyLogic->getMenu(true);
    	
    	$classify = array();
    	
    	foreach ($menu as $v){
    		$button = array();
    	    if(!empty($v['_child'])){
    	        foreach ($v['_child'] as $vv){
    	        	$vv['config'] = serializeMysql($vv['config'],1);
    	            if($vv['config']['msgtype'] == 'url'){
    	                $button['sub_button'][] = array(
    	                    'type'=>'view',
    	                	'name'=>$vv['title'],
    	                	'url'=>$vv['config']['url']
    	                );
    	            }else{
    	            	$button['sub_button'][] = array(
    	            			'type'=>'click',
    	            			'name'=>$vv['title'],
    	            			'key'=>$vv['config']['msgtype'].'_'.$vv['config']['msgid']
    	            	);
    	            }
    	        }
    	        $button['name'] = $v['title'];
    	    }else{
    	    	$v['config'] = serializeMysql($v['config'],1);
    	    	if($v['config']['msgtype'] == 'url'){
    	    		$button = array(
    	    				'type'=>'view',
    	    				'name'=>$v['title'],
    	    				'url'=>$v['config']['url']
    	    		);
    	    	}else{
    	    		$button = array(
    	    				'type'=>'click',
    	    				'name'=>$v['title'],
    	    				'key'=>$v['config']['msgtype'].'_'.$v['config']['msgid']
    	    		);
    	    	}
    	    }
    	    
    	    $classify['button'][] = $button;
    	}
    	
    	$data = json_encode($classify);
		$data = preg_replace("/\\\u([0-9a-f]{4})/ie", "iconv('UCS-2', 'UTF-8', pack('H*', '$1'));", $data);
    	$res = \Com\Wechat\ThinkWechat::publish_classify($access_token,$data);
    	
    	if(isset($res['errcode']) && $res['errcode'] == 0){
    		$data = array(
    				'status'=>1,
    				'msg'=>'添加成功'
    		);
    	}else{
    		$data = array(
    				'status'=>0,
    				'msg'=>$res['errmsg'],
    		);
    	}
    	
       $this->ajaxReturn($data,'JSON');
    	
    }
    
    /**
     * 删除已经发布的自定义菜单
     */
    public function delPublishedClassify(){
    	
    	$userconfigLogic = D('Userconfig','Logic');
    	 
    	//获取用户accesstoken
    	$access_token = $userconfigLogic->access_token();
    	
    	//     	dump($access_token);exit;
    	
    	//判断是不是正确的值
    	if(empty($access_token) || isset($access_token['errcode'])){
    		//     	    $this->error('获取access_token错误,'.$access_token['errmsg']);
    		$data = array(
    				'status'=>0,
    				'msg'=>'获取access_token错误,'.$access_token['errmsg']
    		);
    		$this->ajaxReturn($data,'JSON');
    	}
    	 
    	$res = \Com\Wechat\ThinkWechat::delPublishedClassify($access_token['access_token']);
    	 
    	if(isset($res['errcode']) && $res['errcode'] == 0){
    		$data = array(
    				'status'=>1,
    				'msg'=>'添加成功'
    		);
    	}else{
    		$data = array(
    				'status'=>0,
    				'msg'=>$res,
    		);
    	}

    	
    	 
    	$this->ajaxReturn($data,'JSON');
    }
    
    /**
     * 关键词回复设置
     */
    public function keyword(){
    	
    	$map = array(
    	    'uid'=>UID,
    		array(
    				'msgtype'=>array('IN',array('text','news')),
    				'msgid'=>0,
    				'_logic'=>'OR'
    		),
    	);
    	
    	$keywordsLogic = D('Keywords','Logic');
    	
    	$count = $keywordsLogic->where($map)->count();
    	$page = new Page($count,20);
    	$show       = $page->show();// 分页显示输出
    	// 		dump($show);exit();
    	// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    	$list = $keywordsLogic->where($map)->order('id ASC')->limit($page->firstRow.','.$page->listRows)->select();
    	
    	$textmsgLogic = D('Textmsg','Logic');
    	$newsmsgLogic = D('Newsmsg','Logic');
    	
    	foreach ($list as &$v){
    	    if($v['msgtype'] == 'text'){
    	        $text = $textmsgLogic->detail($v['msgid']);
    	        $v['content'] = $text['text'];
    	    }else{
    	    	$news = $newsmsgLogic->detail($v['msgid']);
    	    	$v['content'] = $news['title'];
    	    }
    	}
//     	dump($list);
    	$this->assign('lists',$list);// 赋值数据集
    	$this->assign('page',$show);// 赋值分页输出
    	$this->display();
    }
    
    /**
     * 添加或者修改关键词
     */
    public function keywordShow($id = 0){
    	
        if(IS_POST){
            $keywordsLogic = D('Keywords','Logic');
            
            $data = $keywordsLogic->create();
            
            $data['uid'] = UID;
            
            $msgtype = I('post.ReplyMsgType','0','intval');
            //如果是文本消息
            if($msgtype == 0){
                $data['msgtype'] = 'text';
                $data['text'] = I('post.text','');
            }else{
            	$MaterialId = I('post.MaterialId');
            	if(intval($MaterialId) > 0){
            		$data['msgtype'] = 'news';
            		$data['msgid'] = intval($MaterialId);
            	}else{
            		$data['msgtype'] = $MaterialId;
            		$data['msgid'] = 0;
            	}
            }
            
            $boolean = $keywordsLogic->saveData($data);
            if($boolean ){
                redirect(U('keyword'));
            }else{
                $this->error('修改失败');
            }
        }else{
        	if($id > 0){
        		$keywordsLogic = D('Keywords','Logic');
        		$keyword = $keywordsLogic->where(array('id'=>$id,'uid'=>UID))->find();
        		$this->assign('keyword',$keyword);
        		
        		if($keyword['id'] > 0 && $keyword['msgtype'] == 'text' && $keyword['msgid'] > 0){
        			$textmsgLogic = D('Textmsg','Logic');
        		    $text = $textmsgLogic->where(array('id'=>$keyword['msgid'],'uid'=>UID))->field('id,text')->find();
        		    $this->assign('textmsg',$text);
        		}else if($keyword['id'] > 0 && in_array($keyword['msgtype'], array('news','onenews')) && $keyword['msgid'] > 0){
        			$newsmsgLogic = D('Newsmsg','Logic');
        			$newsmsg = $newsmsgLogic->detail($keyword['msgid']);
        			$this->assign('newsmsg',$newsmsg);
        		}
        	}
        	
//         	dump($keyword);
        	
        	//获取全部的模块信息
        	$moudleLogic = D('Module','Logic');
        	$modules = $moudleLogic->allLists();
        	$this->assign('modules',$modules);
        	
        	//获取全部的图文消息
        	$newsmsgLogic = D('Newsmsg','Logic');
        	$newsmsgs = $newsmsgLogic->allLists();
        	$this->assign('newsmsgs',$newsmsgs);
        	
            $this->display();
        }
    }
    
    /**
     * 删除关键词信息
     */
    public function delkeyword(){
    	
    	$map=array(
    			'id' => I('get.id')
    	);
    	
    	$keywordsLogic = D('Keywords','Logic');
    	
    	$data=$keywordsLogic->where($map)->delete();
    	
    	if($data){
    		$this->success('删除成功！',U('keyword'));
    	}else{
    		$this->error('删除失败',U('keyword'));
    	}
        
    }
    
    /**
     * token设置
     */
    public function token(){
    	
    	$memberLogic = D('Member','Logic');
    	//判断用户是否是普通
    	$userinfo = $memberLogic->info(UID);
    	$this->assign('userinfo',$userinfo);
    	
    	$this->assign('api_url',make_api_url());
    	
    	//获取用户是否配置了微信帐号
    	$WeixinLogic = D('Weixin','Logic');
    	$weixin = $WeixinLogic->detail();
    	
    	
    	if(empty($weixin)){
    		$this->display('setWeixin');
    	}else{
    		$this->assign('weixin',$weixin);
    		$this->display();
    	}
    	
    }
    /**  
    * 删除绑定信息 
    * @param unknowtype 
    * @return return_type 
    * @author 明 
    * @date 2014-10-6下午7:09:10
    * @version v1.0.0 
    */
    public function delWeixin(){
    	$weixinLogic = D('weixin','Logic');
    	$res = $weixinLogic->where(array('uid'=>UID))->delete();
    	if(!$res){
			 $this->success('解绑失败！'); 		
    	}else{
    		$this->success('解绑成功！',U('Wechat/token'));
    	}
    }
    
    /**
     * 设置微信账号
     */
    public function setWeixin(){
        if(IS_POST){
        	
        	$weixin = I('post.weixin','','trim');
        	
        	$WeixinLogic = D('Weixin','Logic');
        	$map = array(
        	    'weixin'=>$weixin,
        		'uid'=>UID
        	);
        	$wei = $WeixinLogic->where($map)->find();
        	if(!empty($wei)){
        	    $this->ajaxReturn(array('msg'=>'您之前已经绑定该账号'));
        	}
        	$data = array(
        	    'id'=>UID,
        	    'uid'=>UID,
        	    'weixin'=>$weixin,
        		'addtime'=>time(),
        	);
        	$res = $WeixinLogic->add($data);
        	if($res !== false){
        		$this->ajaxReturn(array('status'=>'1','jumpurl'=>U('setWeixin2')));
        	}else {
        		$this->ajaxReturn(array('msg'=>'操作失败'));
        	}
        }
    }
    
    /**
     * 设置微信账号
     */
    public function setWeixin2(){
    	
    	if(IS_POST){
    	    $this->ajaxReturn(array('status'=>'1','jumpurl'=>U('token')));
    	}
    	
    	$memberLogic = D('Member','Logic');
    	//判断用户是否是普通
    	$userinfo = $memberLogic->info(UID);
    	$this->assign('userinfo',$userinfo);
    	 
    	$this->assign('api_url',make_api_url());
    	
    	$this->display('Wechat/setWeixin2');
    }
    
    /**
     * 授权设置
     */
    public function auth(){
    	
    	$userconfig = D('Userconfig','Logic');
    	
    	if(IS_POST){
    	   
    	    $boolean = $userconfig->update();
    	    if($boolean){
    	        $this->success('修改成功');
    	    }else{
    	        $this->error('修改失败');
    	    }
    	}else{
    		$userconfig = $userconfig->detail();
    		//dump($userconfig);
    		$this->assign('userconfig',$userconfig);
    		$this->display();
    	}
    	
    	
    }
    
    
    /**
     * 关注用户列表
     */
    public function users(){
        
    }
    /**
    * 支付和运费
    * @date: 2014-10-21
    * @author: 明
    * @return:
    */
    public function pay(){
    	$MallPayLogic = D('MallPay','Logic');
    	if(IS_POST){
    		$wxpay = array();
    		$wxpay_enable = I('post.PaymentWxpayEnabled',0,'intval');
    		if($wxpay_enable == 1){
    			$wxpay['enable'] = 1;
    			$wxpay['mchid'] = I('post.PaymentWxpayMchId',0,'trim');
    			$wxpay['partnerkey'] = I('PaymentWxpayPartnerKey',0,'trim');
    		}else{
    			$wxpay['enable'] = 0;
    		}
    			
    		$offline = array();
    		$offline_enable = I('post.PaymentInfoEnabled',0,'intval');
    		if($offline_enable == 1){
    			$offline['enable'] = 1;
    			$offline['account'] = I('post.PaymentInfo','','trim');
    		}else {
    			$offline['enable'] = 0;
    		}
    		$config = serializeMysql(array('wxpay'=>$wxpay,'offline'=>$offline));
    		
    			
    		$boolean = $MallPayLogic->update(array('configs'=>$config));
    			
    		if ($boolean){
    			$this->ajaxReturn(array('status'=>1));
    		}else{
    			$this->ajaxReturn(array('msg'=>$MallPayLogic->getError()));
    		}
    	}else{
    		$pay = $MallPayLogic->detail();
    		$this->assign('pay',$pay);
    		$this->display();
    	}
    }
    /**
     * 工具箱
     */
    public function tools(){
        if(IS_POST){
            
        }else {
        	$toolsLogic =D('Tools','Logic');
        	$chengyu = $toolsLogic->where(array('uid'=>UID,'tool'=>'chengyu'))->find();
        	$fanyi = $toolsLogic->where(array('uid'=>UID,'tool'=>'fanyi'))->find();
        	$quhao = $toolsLogic->where(array('uid'=>UID,'tool'=>'quhao'))->find();
        	$shouji = $toolsLogic->where(array('uid'=>UID,'tool'=>'shouji'))->find();
        	$tianqi = $toolsLogic->where(array('uid'=>UID,'tool'=>'tianqi'))->find();
        	$xiaohua = $toolsLogic->where(array('uid'=>UID,'tool'=>'xiaohua'))->find();
        	$youbian = $toolsLogic->where(array('uid'=>UID,'tool'=>'youbian'))->find();
        	$ip = $toolsLogic->where(array('uid'=>UID,'tool'=>'ip'))->find();
        	$shenfenzheng = $toolsLogic->where(array('uid'=>UID,'tool'=>'shenfenzheng'))->find();
        	$this->assign('chengyu',$chengyu);
        	$this->assign('fanyi',$fanyi);
        	$this->assign('quhao',$quhao);
        	$this->assign('shouji',$shouji);
        	$this->assign('tianqi',$tianqi);
        	$this->assign('xiaohua',$xiaohua);
        	$this->assign('youbian',$youbian);
        	$this->assign('ip',$ip);
        	$this->assign('shenfenzheng',$shenfenzheng);
        	$this->display();
        }

    }
    
    /**  
    * 设置工具箱 
    * @param unknowtype 
    * @return return_type 
    * @author 明 
    * @date 2014-9-17下午6:52:49
    * @version v1.0.0 
    */
    public function toolsconfig(){
    	$uid = UID;
    	$tool = I('get.tool');
    	$status = I('get.Status');
    	$toolsLogic = D('tools','Logic');
    	$data = array(
    		'status' => $status,
    		'uid' => UID,
    		'tool'=>$tool	
    	);
    	$res = $toolsLogic->where(array('uid'=>$uid,'tool'=>$tool))->find();
    	if(!$res){
    		$res = $toolsLogic->add($data);
    		if($res){
    			$this->ajaxReturn(array('ret'=>1));
    		}else {
    			$this->ajaxReturn(array('ret'=>0));
    		}
    	}else {
    		$res = $toolsLogic->where(array('uid'=>$uid,'tool'=>$tool))->save($data);
    		if($res){
    			$this->ajaxReturn(array('ret'=>1));
    		}else {
    			$this->ajaxReturn(array('ret'=>0));
    		}
    	}
    	
    }
    
    public function announcement(){
    	//获取公告信息
    	$announcementLogic = D('Announcement','Logic');
    	$map = array(
    			'usertype'=>array('IN',array('2','3'))
    	);
    	
    	 
    	$count = $announcementLogic->where($map)->count();
    	$page = new Page($count,20);
    	$show       = $page->show();// 分页显示输出
    	// 		dump($show);exit();
    	// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    	$list = $announcementLogic->where($map)->order('id ASC')->limit($page->firstRow.','.$page->listRows)->select();
    	 
    	$this->assign('lists',$list);// 赋值数据集
    	$this->assign('page',$show);// 赋值分页输出
    	
    	
    	$announcement = $announcementLogic->where($map)->order('id DESC')->select();
    	$this->assign('announcement',$announcement);
    	$this->display();
    }
    
    /**
    * 验证模糊查询
    * @date: 2014-12-9
    * @author: 明
    * @return:
    */
    public function keyseach(){
    	$map = array(
    			/* array(
    				'EXP','"会员"'.'REGEXP'
    			) => 'keyword', */
    			'keyword' =>array(
    				'EXP','REGEXP'.'会员'
    			), 
    			'uid'=>2,
    	);
    	$keywordsLogic = D('keywords','Logic');
    	
    	$keywords = $keywordsLogic->where($map)->where('"会员卡" REGEXP keywords')->find();
    	echo $keywordsLogic->getLastSql();
    }
	/**
	* 顺序
	* @date: 2015-1-21
	* @author: 琴
	* @return:
	*/
    
    public function sortorder(){
    	$classifyLogic = D('Classify','Logic');
    	$sort =I('post.sort_order');
    	foreach($sort as $key=>$value){
    		$classify[$key] = $classifyLogic->where(array('id'=>$value))->save(array('sort'=>$key));
    	}
    	$this->ajaxReturn(array('status'=>1));
    }
    
    
    
}